﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 台签打印
{
    public class RectangleEdges
    {
        // 定义线段结构（包含起点终点）
        public struct Edge : IEquatable<Edge>
        {
            public Point Start { get; }
            public Point End { get; }

            public Edge(Point start, Point end)
            {
                // 标准化线段方向：水平线从左到右，垂直线从上到下
                if (start.X == end.X) // 垂直线
                {
                    Start = start.Y <= end.Y ? start : end;
                    End = start.Y <= end.Y ? end : start;
                }
                else // 水平线
                {
                    Start = start.X <= end.X ? start : end;
                    End = start.X <= end.X ? end : start;
                }
            }

            public bool Equals(Edge other) =>
                Start.Equals(other.Start) && End.Equals(other.End);

            public override string ToString() =>
                $"{Start.X},{Start.Y} → {End.X},{End.Y}";
        }

        /// <summary>
        /// 获取矩形的四条标准化边线
        /// </summary>
        /// <param name="rect">输入矩形</param>
        /// <returns>按顺时针顺序返回四条边</returns>
        public static Edge[] GetEdges(Rectangle rect)
        {
            // 计算四角坐标（符合GDI+坐标系规范）
            Point topLeft = new Point(rect.Left, rect.Top);
            Point topRight = new Point(rect.Right, rect.Top);
            Point bottomRight = new Point(rect.Right, rect.Bottom);
            Point bottomLeft = new Point(rect.Left, rect.Bottom);

            return new Edge[]
                {
                new Edge(topLeft, topRight),     // 上边
                new Edge(topRight, bottomRight), // 右边
                new Edge(bottomRight, bottomLeft), // 下边
                new Edge(bottomLeft, topLeft)    // 左边
			    };
        }

        /// <summary>
        /// 获取矩形列表的四条边线并去重
        /// </summary>
        /// <param name="rects"></param>
        /// <returns></returns>
        public static IEnumerable<Edge> GetEdges(IEnumerable<Rectangle> rects)
        {
            return rects.SelectMany(rect => GetEdges(rect)).Distinct();
        }

    }
}
